<?php

$nns_db_vod_index_dir = dirname(dirname(__FILE__));
require_once $nns_db_vod_index_dir . DIRECTORY_SEPARATOR . "nns_common" . DIRECTORY_SEPARATOR . "nns_db_class.php";
require_once $nns_db_vod_index_dir . DIRECTORY_SEPARATOR . "nns_common" . DIRECTORY_SEPARATOR . "nns_db_guid_class.php";
include_once $nns_db_vod_index_dir . DIRECTORY_SEPARATOR . "nns_label" . DIRECTORY_SEPARATOR . "nns_label.class.php";
//加载BK配置以及栏目映射
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/models/queue_task_model.php';

class nns_db_vod_index_class {

        private $conn;
        private $db_obj;
		public $message_id = '';
		public $cp_config = '';
		public $conf_info = array();

        public $int_weight = 0;
        public $is_group = 0;

        public function __construct() {
                $this->db_obj = new nns_db_class(g_db_host, g_db_username, g_db_password, g_db_name);
                $this->conn = $this->db_obj->nns_db_connect();
        }

        /**
         * 权重设置
         * @param unknown $int_weight
         */
        public function _set_weight($int_weight)
        {
            $int_weight = (int) $int_weight;
            $this->int_weight = $int_weight >0 ? $int_weight : 0;
        }
        
        /**
         * 获取权重
         */
        public function _get_weight()
        {
            $int_weight = (int) $this->int_weight;
            return $int_weight >0 ? $int_weight : 0;
        }

        /**
         * 设置消息中的内容是否为分组消息
         * @param $int_weight
         */
        public function _set_is_group($is_group)
        {
                $is_group = (int) $is_group;
                $this->is_group = $is_group >0 ? $is_group : 0;
        }

        /**
         * 获取消息中内容是否分组消息
         * @return int
         */
        public function _get_is_group()
        {
                $is_group = (int) $this->is_group;
                return $is_group >0 ? $is_group : 0;
        }
        
        //索引统计
        public function nns_db_vod_index_count($vod_id = null, $name = null, $order = null) {
                $result = array();
                $str_sql = "select count(1) as num from nns_vod_index ";
                $where = "";
                //vod_id
                if (isset($vod_id)) {
                        if (!empty($vod_id)) {
                                if (empty($where)) {
                                        $where .= " where nns_vod_id='$vod_id'";
                                } else {
                                        $where .= " or nns_vod_id='$vod_id'";
                                }
                        }
                }
                //name
                if (isset($name)) {
                        if (!empty($name)) {
                                if (empty($where)) {
                                        $where .= " where nns_name like '%$name%'";
                                } else {
                                        $where .= " or nns_name like '%$name%'";
                                }
                        }
                }
                if (isset($order)) {
                        if (empty($order)) {
                                $where .= " order by nns_modify_time desc";
                        } else {
                                $where .= " order by $order desc";
                        }
                }
                $str_sql .= $where;
                $result = $this->db_obj->nns_db_query($str_sql);
                return $result;
        }

        //索引列表
        public function nns_db_vod_index_list($vod_id = '', $name = '', $order = '', $min = 0, $num = 0) {
                $result = array();
                $str_sql = "select * from nns_vod_index ";
                $where = "";
                //vod_id
                if (isset($vod_id)) {
                        if (!empty($vod_id)) {
                                if (empty($where)) {
                                        $where .= " where nns_vod_id='$vod_id'";
                                } else {
                                        $where .= " and nns_vod_id='$vod_id'";
                                }
                        }
                }
                //vod_id
                if (isset($name)) {
                        if (!empty($name)) {
                                if (empty($where)) {
                                        $where .= " where nns_name like '%$name%'";
                                } else {
                                        $where .= " and nns_name like '%$name%'";
                                }
                        }
                }
                if (isset($order)) {
                        if (empty($order)) {
                                $where .= " order by nns_index asc";
                        } else {
                                $where .= " order by $order desc";
                        }
                }
                if (isset($min) && isset($num)) {
                        if (!empty($num)) {
                                $min = (int) $min;
                                $num = (int) $num;
                                $where .= " limit $min,$num";
                        }
                }
                $str_sql .= $where;
                $result = $this->db_obj->nns_db_query($str_sql);
                if ($result ["ret"] == 0) {
                        if ($this->db_obj->num_rows <= 0) {
                                $result = $this->db_obj->nns_db_result(NNS_ERROR_VOD_INDEX_NOT_FOUND, 'vod index data not find');
                        }
                }
                return $result;
        }

        //索引详细信息
        public function nns_db_vod_index_info($vod_id, $index,$flag=true) {
                $result = array();
                //vod_id
                if (!isset($vod_id)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index info param error');
                        return $result;
                }
                if (empty($vod_id)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index info param error');
                        return $result;
                }
                //index
                if (!isset($index)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index info param error');
                        return $result;
                }
                if ($index === null || $index === '') {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index info param error');
                        return $result;
                }
                $index = (int) $index;

                $str_delete = '';
                if($flag)
                {
                	$str_delete=' and nns_deleted!=1 ';
                }
                
                $str_sql = "select * from nns_vod_index where nns_vod_id='$vod_id' and nns_index=$index  {$str_delete} ";
                $result = $this->db_obj->nns_db_query($str_sql);
                if ($result ["ret"] == 0) {
                        if ($this->db_obj->num_rows <= 0) {
                                $result = $this->db_obj->nns_db_result(NNS_ERROR_VOD_INDEX_NO_DATA, 'vod index data not find');
                        }
                }
                return $result;
        }

        //索引详细信息
        public function nns_db_vod_index_info_by_indexid($index_id) {
                $result = array();
                //vod_id
                if (!isset($index_id)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index info param error');
                        return $result;
                }
                if (empty($index_id)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index info param error');
                        return $result;
                }
                $str_sql = "select * from nns_vod_index where nns_id='$index_id'";
                $result = $this->db_obj->nns_db_query($str_sql);
                if ($result ["ret"] == 0) {
                        if ($this->db_obj->num_rows <= 0) {
                                $result = $this->db_obj->nns_db_result(NNS_ERROR_VOD_INDEX_NO_DATA, 'vod index data not find');
                        }
                }
                return $result;
        }

        //修改index 简介
        public function nns_db_vod_index_modify($vod_id, $index, $name = null, $time_len = null, $image = null, $summary = null, $nns_director = NULL, $nns_actor = NULL,
            $import_source = NULL, $import_id = NULL,$nns_release_time=null,$nns_cp_id=null) {
                $nns_actor = np_build_split_string($nns_actor, '/', false);
                $nns_director = np_build_split_string($nns_director, '/', false);
                $result = array();
                $where = "";
                if (!isset($vod_id) || !isset($index)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index modify param error');
                        return $result;
                }
                if (empty($vod_id)) {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index modify param error');
                        return $result;
                }
                if ($index === null && $index === '') {
                        $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index modify param error');
                        return $result;
                }
                $index = (int) $index;
                $time_len = (int) $time_len;
                if(strlen($nns_cp_id) <1)
                {
                	$nns_cp_id = 0;
                }
                $str_import_source =  '';
                if(strlen($import_source) >0)
                {
                    $str_import_source = " and nns_import_source='{$import_source}' ";
                }
                else
                {
                    $import_source='';
                }
                //index exist
                $str_sql = "select nns_id from nns_vod_index where nns_vod_id='$vod_id' and nns_index=$index and nns_deleted!=1 {$str_import_source} ";
                $result = $this->db_obj->nns_db_query($str_sql);
                if ($result ["ret"] != 0) {
                        return $result;
                }
                
                if ($this->db_obj->num_rows <= 0) 
                {
                	if(strlen($import_source) <1)
                	{
                		$sql_vod_query = "select * from nns_vod where nns_id='{$vod_id}' limit 1";
                		$result_vod_query = $this->db_obj->nns_db_query($sql_vod_query);
                		if ($result ["ret"] != 0) {
                			return $result;
                		}
                		$import_source = isset($result_vod_query['data'][0]['nns_import_source']) ? $result_vod_query['data'][0]['nns_import_source'] : '';
                	}
                        //insert into index
                        //生成vod index GUID
                        if(!empty($nns_release_time)){
                            if(strlen($nns_release_time) !=19){
							$nns_release_time = $nns_release_time.' 00:00:00';
                            }
						}
						else
						{
						    $nns_release_time = date('Y-m-d',time()).' 00:00:00';
						}
                        $guid = new Guid ();
                        $index_id = $guid->toString();
                        $str_sql = "insert into nns_vod_index(nns_id,nns_vod_id,nns_index,nns_name,nns_time_len,nns_image,nns_summary,nns_create_time,nns_modify_time,nns_import_source,nns_import_id,nns_director,nns_actor,nns_status,nns_action,nns_release_time,nns_cp_id)values('$index_id','$vod_id',$index,'$name',$time_len,'$image','$summary',now(),now(),'$import_source','$import_id','$nns_director','$nns_actor',1,'add','$nns_release_time','$nns_cp_id')";
                        $result = $this->db_obj->nns_db_execute($str_sql);
                        if ($result['ret'] == 0) {
                                $g_inject = g_cms_config::get_g_config_value('g_inject_enabled');
								if($g_inject){

									//category_content_model::_task_c2_v2($index_id, BK_OP_INDEX, BK_OP_ADD);
									$queue_task_model = new queue_task_model();
                                    $queue_task_model->_set_weight($this->_get_weight());
                                    $queue_task_model->_set_is_group($this->_get_is_group());
									$queue_task_model->q_add_task_op_mgtv($index_id, BK_OP_INDEX, BK_OP_ADD,$this->message_id,true,$this->conf_info);
									unset($queue_task_model);
								}	
                                //			加入标签
                                $label_inst = new nns_label();
                                $label_inst->add_label(
                                        $index_id, 3, array(
                                    'actor' => $nns_actor,
                                    'director' => $nns_director
                                        )
                                );
                        }
                } else {
                	if(strlen($import_source) <1)
                	{
                		$sql_vod_query = "select * from nns_vod where nns_id='{$vod_id}' limit 1";
                		$result_vod_query = $this->db_obj->nns_db_query($sql_vod_query);
                		if ($result ["ret"] != 0) {
                			return $result;
                		}
                		$import_source = isset($result_vod_query['data'][0]['nns_import_source']) ? $result_vod_query['data'][0]['nns_import_source'] : '';
                	}
                        $guid = $result['data'][0]['nns_id'];
                        $img_str = '';
                        if (!empty($image)) {
                                $img_str .= ",nns_image='$image'";
                        }
						if(!empty($nns_release_time)){
							 $nns_release_time = $nns_release_time.' 00:00:00';
							 $img_str .= ",nns_release_time='$nns_release_time'";
						}
						if(strlen($nns_cp_id) > 0)
						{
							$img_str = ",nns_cp_id='$nns_cp_id'";
						}
						else
						{
							$img_str = ",nns_cp_id='0'";
						}
                        //update
                        
                        $str_sql = "update nns_vod_index set nns_import_source='$import_source',nns_import_id='$import_id',nns_deleted=0,nns_name='$name',nns_time_len=$time_len ,nns_summary='$summary',nns_modify_time=now()" . $img_str . ",nns_director='$nns_director',nns_actor='$nns_actor',nns_status=2,nns_action='modify' where nns_vod_id='$vod_id' and nns_index=$index";
                        
                        $result = $this->db_obj->nns_db_execute($str_sql);
                        if ($result['ret'] == 0) {
                        		$g_inject = g_cms_config::get_g_config_value('g_inject_enabled');
								if($g_inject){

									$queue_task_model = new queue_task_model();
                                    $queue_task_model->_set_weight($this->_get_weight());
									$queue_task_model->_set_weight($this->_get_weight());
									$queue_task_model->q_add_task_op_mgtv($guid, BK_OP_INDEX, BK_OP_MODIFY,$this->message_id,true,$this->conf_info);
									unset($queue_task_model);						
																					
								}
                                //			加入标签
                                $label_inst = new nns_label();
                                $label_inst->delete_label(
                                        $guid, 3
                                );
                                $label_inst->add_label(
                                        $guid, 3, array(
                                    'actor' => $nns_actor,
                                    'director' => $nns_director
                                        )
                                );
                        }
                }
				//对于同步剧的处理				
// 				$g_inject = g_cms_config::get_g_config_value('g_inject_enabled');
// 				if($g_inject){
// 					$queue_task_model = new queue_task_model();
// 					$queue_task_model->q_add_task_op_mgtv($vod_id, BK_OP_VIDEO, BK_OP_MODIFY,$this->message_id);
// 					unset($queue_task_model);
// 				}
                return $result;
        }

//  根据ID删除分片
        public function nns_db_vod_index_delete($id, $bool = TRUE,$cp_id=null) 
        {
            //更新任务表里面的状态
                				
				$str_sql = "update nns_vod_index set nns_deleted=1,nns_status=3,nns_action='destroy',nns_modify_time=now() where nns_id='$id'";
				if(strlen($cp_id) > 0)
				{
					$str_sql.=" and nns_cp_id='{$str_sql}'";
				}           
               // $str_sql = "delete from nns_vod_index where nns_id='{$id}'";
                $result = $this->db_obj->nns_db_execute($str_sql);

                if ($result['ret'] == 0) 
                {
                	include_once 'nns_db_vod_media_class.php';
                   	$str_sql = "select nns_id from nns_vod_media where nns_vod_index_id='{$id}' and nns_deleted!=1";
                    if(strlen($cp_id) > 0)
                    {
                    	$str_sql.=" and nns_cp_id='{$str_sql}'";
                    }
                   	$media_data = $this->db_obj->nns_db_query($str_sql);
                   	$vod_media_inst = new nns_db_vod_media_class();
					$vod_media_inst->message_id = $this->message_id;
					$sync_delete_media_with_index = (isset($this->cp_config['sync_delete_media_with_index']) && (int)$this->cp_config['sync_delete_media_with_index'] === 1) ? false : true;			
                   	if(is_array($media_data['data']))
                    {
	                	foreach ($media_data['data'] as $media_item) 
	                	{
	                    	$vod_media_inst->nns_db_vod_media_delete($media_item['nns_id'], $sync_delete_media_with_index);
	                    }
                    }
                   	$vod_media_inst = NULL;
                   	$label_inst = new nns_label();
                   	$label_inst->delete_label(
                    	$id, 3
                    );
                }
				
				$g_inject = g_cms_config::get_g_config_value('g_inject_enabled');
				if($g_inject){
					//$g_bk_mode = g_cms_config::get_g_config_value('g_bk_mode');
					//if(empty($g_bk_mode)){
						//category_model::delete_category_content($id,'index');
						//取消该分集的任务
						//include_once dirname(dirname(dirname(__FILE__))) . "/mgtv/fjyd/models/clip_task_model.php";
						//clip_task_model::cancel_task_by_vod_index($id);
					//}elseif($g_bk_mode==1){
						//category_content_model::_task_c2_v2($id, BK_OP_INDEX, BK_OP_DELETE);
					//}

                    //广西删除逻辑不生成队列
                    $g_delete_enable_center_import_v2 = get_config_v2('g_delete_enable_center_import_v2');
                    if($g_delete_enable_center_import_v2 != 1)
                    {
                        $queue_task_model = new queue_task_model();
                        $queue_task_model->_set_weight($this->_get_weight());
                        $queue_task_model->_set_is_group($this->_get_is_group());
                        $queue_task_model->q_add_task_op_mgtv($id, BK_OP_INDEX, BK_OP_DELETE, $this->message_id);
                        //error_log($id.'-----index'.PHP_EOL,3,'txt.log');
                        unset($queue_task_model);
                    }
				} 
        }

        /**
         * 通过导入ID及分片号 获取CMS平台ID
         * @param String 来源
         * @param String 来源ID
         * @param String 来源分片数
         * @return array(
         * 				'nns_id'=>分片ID
         * 				'nns_vod_id'=>影片ID
         * 			) 
         * 			FALSE 无此ID
         */
        public function get_video_index_id_by_import_id($import_source, $import_id, $index_num = NULL, $is_index = false,$asset_id=false,$cp_id=null,$check_enabled=1) 
        {
                $str_sql = "select nns_id,nns_vod_id,nns_index from nns_vod_index where " .                     		
                        "( nns_import_id='{$import_id}'  and nns_deleted!=1";
                if ($index_num !== null && $index_num !== '') {
                        if ($is_index == true)
                                $str_sql.=" AND nns_index='{$index_num}'";
                        else
                                $str_sql.=" or nns_index='{$index_num}'";
                }
                $str_sql.=')';
				
				if($asset_id){
					$str_sql .= " and nns_vod_id='{$asset_id}'";
				}
				
				if (strlen($cp_id) < 1)
				{
					$cp_id = 0;
				}
				$str_sql.=" and nns_cp_id='{$cp_id}'";
				if($check_enabled)
				{
					$str_sql .= " and nns_import_source='{$import_source}'";
				}
                $result = $this->db_obj->nns_db_query($str_sql);
                if (count($result['data']) > 0) {
                        return $result['data'][0];
                } else {
                        return FALSE;
                }
        }

}

?>